package cn.template.models;

import cn.template.enums.UserRole;
import cn.template.services.UserService;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.*;

@Data
@Entity
@DynamicUpdate
@Table(name = "users")
public class User extends BaseObject<User> {
    private String name;
    private String tel;
    @Column(unique = true)
    private String username;
    private String password;
    private String idNumber;
    @ElementCollection
    private List<UserRole> userRoles = new ArrayList<>();
    @ManyToOne(targetEntity = Company.class, cascade = {CascadeType.PERSIST}, fetch = FetchType.LAZY)
    private Company company;

    public User() {
    }

    public User(String name, String tel, String username) {
        this.name = name;
        this.tel = tel;
        this.username = username;
        this.userRoles.add(UserRole.GeneralUser);
    }

    public void addRole(UserRole userRole) {
        if (this.userRoles.indexOf(userRole) == -1) {
            this.userRoles.add(userRole);
        }
    }

    public void removeRole(UserRole userRole) {
        if (this.userRoles.indexOf(userRole) > -1) {
            this.userRoles.remove(userRole);
        }
    }

    @Override
    public void update(User source) {
        this.name = source.getName();
        this.username = source.getUsername();
        this.userRoles = source.getUserRoles();
        this.tel = source.getTel();
        this.idNumber = source.getIdNumber();
        this.company = source.getCompany();
        if (!source.getPassword().isEmpty()) {
            String encoded = UserService.encodePassword(source.getPassword());
            if (!this.getPassword().equals(encoded)) {
                this.password = encoded;
            }
        }
    }
}